<template>
	<view>
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="ID" label="商户统一编号" required>
				<view class="shop-id-box">
					<text>{{formData.ID?formData.ID:'唯一编号,输入门牌号后系统自动识别生成'}}</text>
				</view>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="address" label="商户门牌号" required>
				<text style="color: #888;font-size: 26rpx;line-height: 1.05;">门牌号码不可修改。</text>
				<uni-easyinput placeholder="商户门牌号" v-model="formData.address.address_number" disabled
					@input="addressInput" trim />
			</uni-forms-item>
			<uni-forms-item class="align-items-center background" name="shop_name" label="商户名称" required>
				<view class="shop-name-note">
					<text>全称</text>
				</view>
				<uni-easyinput style="margin-bottom: 20rpx;" placeholder="全称" v-model="formData.shop_name.full_name"
					trim />
				<view class="shop-name-note">
					<text>简称</text>
				</view>
				<uni-easyinput placeholder="简称" v-model="formData.shop_name.short_name" />
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="logo_src" label="商户logo">
				<cloud-image-alioss prefix="logo_" uploadDir="henghui/images"
					v-model="formData.logo_src"></cloud-image-alioss>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="banner" label="门头图片">
				<cloud-image-alioss prefix="banner_" uploadDir="henghui/images"
					v-model="formData.banner"></cloud-image-alioss>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="business_license" label="营业执照">
				<cloud-image-alioss prefix="banner_" uploadDir="henghui/images"
					v-model="formData.business_license"></cloud-image-alioss>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="shop_desc" label="商户简介">
				<uni-easyinput type="textarea" placeholder="商户简介 文字" v-model="formData.shop_desc" />
			</uni-forms-item>
			<uni-forms-item name="location" label="商铺位置" required>
				<view class="" v-if="showLocation">
					<view class="">
						<text class="font-28 color-555">名称：</text>
						<text class="font-28 color-555">{{formData.location.name}}</text>
					</view>
					<view class="">
						<text class="font-28 color-555">地址：</text>
						<text class="font-28 color-555">{{`乌鲁木齐市头屯河区头屯河公路2201号 新疆恒汇机电城 ${formData.address.address_number} 号`}}</text>
					</view>
					<view class="">
						<text class="font-28 color-555">位置的经纬度：</text>
						<text
							class="font-28 color-555">{{`[${formData.location.longitude}, ${formData.location.latitude}]`}}</text>
					</view>
				</view>
				<view class="location-box" @click="toChooseLocation">
					<text class="colorGray margin-right-20">请在地图上选择商铺位置</text>
					<wjf-iconfont code="e7b3" color="deepskyblue" size="15"></wjf-iconfont>
				</view>
			</uni-forms-item>
			<uni-forms-item class="align-items-center background" name="phone" label="联系电话" required>
				<uni-easyinput style="margin-bottom: 20rpx;" placeholder="对外销售电话" type="number"
					v-model="formData.phone.contact" trim />
				<uni-easyinput style="margin-bottom: 20rpx;" placeholder="老板或负责人电话" type="number"
					v-model="formData.phone.head" trim />
				<uni-easyinput placeholder="商务合作电话" type="number" v-model="formData.phone.business" trim />
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="website" label="商户官网">
				<uni-easyinput type="textarea" placeholder="商户官网" v-model="formData.website" trim />
			</uni-forms-item>
			<uni-forms-item name="online" label="是否营业">
				<switch @change="binddata('online', $event.detail.value)" :checked="formData.online" />
			</uni-forms-item>
			<uni-forms-item name="state" label="是否启用">
				<switch @change="binddata('state', $event.detail.value)" :checked="formData.state" />
			</uni-forms-item>

		</uni-forms>
		<view class="button-group">
			<navigator open-type="navigateBack" style="margin-left: 30px;">
				<button class="uni-button" style="width: 100px;">返回</button>
			</navigator>
			<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
		</view>
		<uv-modal ref="uvModal" :title="uvModelParam.title" :content='uvModelParam.content' :align="uvModelParam.align"
			:confirmText="uvModelParam.confirmText" :cancelText="uvModelParam.cancelText"
			:showCancelButton="uvModelParam.showCancelButton"></uv-modal>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/tian-mall-shops.js';
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'tian-mall-shops';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}
	import commMixinWjf from '@/common/mixin/common-mixin-wjf.js'
	export default {
		mixins: [commMixinWjf],
		data() {
			return {
				formDataId: '',
				showLocation: false,
				formData: {
					"ID": '', //商户唯一编号，系统自动根据门牌号识别生成
					"address": {
						"address_number": ""
					},
					"banner": "",
					"shop_name": {
						"full_name": '',
						"short_name": ''
					},
					"location": {
						"name": '',
						"latitude": 0,
						"longitude": 0
					},
					"logo_src": "",
					"business_license": "", //营业执照
					"shop_desc": "",
					"website": "",
					"phone": {
						"contact": "",
						"head": "",
						"business": ""
					},
					"online": true,
					"state": true
				},
				rules: {
					...getValidator(["address", "shop_name", "logo_src", "banner", "shop_desc", "phone", "website",
						"online", "state"
					])
				}
			}
		},
		onLoad(option) {
			if (option.id) {
				this.formDataId = option.id
				this.getDetail(option.id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			toChooseLocation() {
				// #ifdef MP-WEIXIN
				wx.chooseLocation({
					success: (res) => {

						this.showLocation = true
						this.formData.location.name = this.formData.shop_name.full_name ? this.formData
							.shop_name.full_name : res.name
						this.formData.location.longitude = res.longitude
						this.formData.location.latitude = res.latitude
						console.log(this.formData.location);
					}
				})
				// #endif
			},
			/**
			 * 触发表单提交
			 */
			async submit() {
				uni.showLoading({
					mask: true
				})
				// validate
				this.$refs.form.validate().then((res) => {
					this.submitForm(res)
				}).catch((errors) => {
					this.$uvModal({
						content: `请注意输入内容的错误提示，有不合规的输入时无法提交。`,
						align: 'center',
					})
					uni.hideLoading()
				})
			},
			submitForm(value) {
				// 使用 clientDB 提交数据
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			addressInput(e) {


				let tt = e.trim().replace(/^0/, '').replace(/d/g, 'D').replace(/[_*+.,，。——-]+/g, '-')
				// 如果输入已经是正确格式，直接返回
				if (/^(\d+)-(\d{2})-(\d{2})$/.test(tt)) {
					setTimeout(() => {
						this.formData.address.address_number = tt
						this.formData.ID = tt

					}, 1)
					return

				} else if (/^(\d+)-(D?\d{2})$/.test(tt)) {
					setTimeout(() => {
						this.formData.address.address_number = tt
						this.formData.ID = tt

					}, 1)
					return
				}

				let newVal = ''
				switch (true) {
					case /^(\d+)-(\d+)-(\d+)$/.test(tt):
						newVal = tt.replace(/^(\d+)-(\d+)-(\d+)$/, (match, g1, g2, g3) => {
							// 补齐后两组数字为两位数
							return `${g1}-${g2.padStart(2, '0').slice(0, 4)}-${g3.padStart(2, '0').slice(0, 4)}`;
						})
						break;
					case /^(\d+)-(D?\d+)$/.test(tt):
						newVal = tt.replace(/^(\d+)-(D?\d{2,4})$/, (match, g1, g2) => {
							// 如果有字母D，确保数字最多两位，补足不足的位
							if (/D/i.test(g2)) {
								return `${g1}-${g2.replace(/(\d+)\d*$/, (num) => num.padStart(2, '0').slice(0, 4))}`;
							} else {
								// 如果没有字母D，确保第二组是两位数字
								return `${g1}-${g2.padStart(2, '0').slice(0, 4)}`;
							}
						})
						break;
					default:
						break;
				}


				setTimeout(() => {
					this.formData.address.address_number = newVal ? newVal : tt
					this.formData.ID = newVal ? newVal : tt
				}, 1)
			},


			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					'ID,address,banner,shop_name,location,logo_src,business_license,shop_desc,website,phone,online,state'
				).get().then((res) => {
					const data = res.result.data[0]
					// console.log(data);
					if (data) {
						this.formData = Object.assign({}, this.formData, data);
					}
					if (this.formData.location) {
						this.showLocation = true
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.top-btn-box {
		display: flex;
		justify-content: flex-end;
		width: 600px;
		height: 80rpx;

		.top-btn {
			background-color: deepskyblue;
			color: #fff;
		}
	}

	.shop-name-note {
		font-size: 24rpx;
		color: #777;
		padding-left: 20rpx;
	}

	.align-items-center {
		display: flex;
		align-items: center;
	}

	.background {
		background-color: #eee;
		padding: 10rpx;
		border-radius: 6rpx;
	}

	.shop-id-box {
		background-color: #efefef;
		width: 50%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 6rpx;

		text {
			color: #999;
		}
	}

	.button-group {
		width: 100%;
		margin: 30rpx 0;
		padding-bottom: 100rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
	}

	.location-box {
		display: flex;
		align-items: center;
		margin-top: 30rpx;
	}
</style>